// 好友模块 - 处理好友关系相关操作
import baseAPI from './base.js'

class FriendAPI {
    // 添加好友
    async addFriend(userId, friendId) {
        return baseAPI.request('/friends/add', {
            method: 'POST',
            body: JSON.stringify({
                user_id: userId,
                friend_id: friendId
            })
        });
    }

    // 获取好友列表
    async getFriends(userId) {
        return baseAPI.request(`/friends?user_id=${userId}`, {
            method: 'GET'
        });
    }

    // 删除好友
    async deleteFriend(userId, friendId) {
        return baseAPI.request('/friends/delete', {
            method: 'POST',
            body: JSON.stringify({
                user_id: userId,
                friend_id: friendId
            })
        });
    }

    // 发送好友请求
    async sendFriendRequest(fromUserId, toUserId, message = '我想加你为好友') {
        return baseAPI.request('/friends/request', {
            method: 'POST',
            body: JSON.stringify({
                from_user_id: fromUserId,
                to_user_id: toUserId,
                message: message
            })
        });
    }

    // 获取好友请求列表
    async getFriendRequests(userId, type = 'received') {
        return baseAPI.request(`/friends/requests?user_id=${userId}&type=${type}`, {
            method: 'GET'
        });
    }

    // 处理好友请求
    async respondToFriendRequest(requestId, userId, action) {
        return baseAPI.request(`/friends/request/${requestId}/respond`, {
            method: 'POST',
            body: JSON.stringify({
                user_id: userId,
                action: action // 'accept' 或 'reject'
            })
        });
    }

    // 取消好友请求
    async cancelFriendRequest(requestId, userId) {
        return baseAPI.request(`/friends/request/${requestId}/cancel`, {
            method: 'POST',
            body: JSON.stringify({
                user_id: userId
            })
        });
    }

    // ==================== 本地离线处理（保留用于兼容） ====================

    // 本地获取好友列表
    handleLocalGetFriends(options) {
        try {
            const url = new URL(`${baseAPI.baseURL}${options.url || ''}`);
            const userId = url.searchParams.get('user_id');
            
            if (!userId) {
                return Promise.reject(new Error('用户ID参数缺失'));
            }
            
            const friendsData = uni.getStorageSync(`friends_list_${userId}`) || '[]';
            const friends = JSON.parse(friendsData);
            
            return Promise.resolve({
                code: 'SUCCESS',
                message: '获取好友列表成功',
                data: friends.map(friend => ({
                    user: {
                        id: friend.id,
                        name: friend.name,
                        email: friend.email,
                        avatar: friend.avatar
                    },
                    remark: friend.name,
                    group: friend.group || '默认分组'
                }))
            });
        } catch (error) {
            return Promise.reject(new Error('获取本地好友数据失败: ' + error.message));
        }
    }

    // 本地发送好友请求
    handleLocalSendFriendRequest(body) {
        try {
            const requestData = JSON.parse(body);
            const { from_user_id, to_user_id, message } = requestData;
            
            // 保存到本地存储
            const userRequestsData = uni.getStorageSync(`friend_requests_${from_user_id}`) || '{"sent": [], "received": []}';
            const userRequests = JSON.parse(userRequestsData);
            
            const newRequest = {
                id: this.generateUserId(),
                from_user_id: from_user_id,
                to_user_id: to_user_id,
                message: message || '我想加你为好友',
                status: 'pending',
                created_at: new Date().toISOString()
            };
            
            userRequests.sent.push(newRequest);
            uni.setStorageSync(`friend_requests_${from_user_id}`, JSON.stringify(userRequests));
            
            return Promise.resolve({
                code: 'SUCCESS',
                message: '好友请求发送成功',
                data: newRequest
            });
        } catch (error) {
            return Promise.reject(new Error('发送本地好友请求失败: ' + error.message));
        }
    }

    // 本地获取好友请求列表
    handleLocalGetFriendRequests(options) {
        try {
            const url = new URL(`${baseAPI.baseURL}${options.url || ''}`);
            const userId = url.searchParams.get('user_id');
            const type = url.searchParams.get('type') || 'received';
            
            if (!userId) {
                return Promise.reject(new Error('用户ID参数缺失'));
            }
            
            const userRequestsData = uni.getStorageSync(`friend_requests_${userId}`) || '{"sent": [], "received": []}';
            const userRequests = JSON.parse(userRequestsData);
            
            const requests = type === 'sent' ? userRequests.sent : userRequests.received;
            
            return Promise.resolve({
                code: 'SUCCESS',
                message: '获取好友请求成功',
                data: requests
            });
        } catch (error) {
            return Promise.reject(new Error('获取本地好友请求数据失败: ' + error.message));
        }
    }

    // 生成用户ID（用于本地模式）
    generateUserId() {
        return Date.now().toString();
    }
}

// 创建全局实例
const friendAPI = new FriendAPI();

export default friendAPI; 